package com.aefottt.struggle_star.util;

import android.content.Context;
import android.content.SharedPreferences;

public class PrefUtil {
    private static PrefUtil mInstance;
    private final Context context;

    private PrefUtil(Context context) {
        this.context = context;
    }

    public static PrefUtil getInstance(Context context){
        if (mInstance == null){
            synchronized (PrefUtil.class){
                if (mInstance == null){
                    mInstance = new PrefUtil(context);
                }
            }
        }
        return mInstance;
    }

    /**
     * 存入数据
     * @param fileName 文件名
     * @param key key值
     * @param value value值
     */
    public void put(String fileName, String key, Object value){
        // 获取类型
        String type = value.getClass().getSimpleName();
        // 实例化Sp
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        switch (type) {
            case "Integer":
                editor.putInt(key, (Integer) value);
                break;
            case "String":
                editor.putString(key, (String) value);
                break;
            case "Boolean":
                editor.putBoolean(key, (Boolean) value);
                break;
            case "Float":
                editor.putFloat(key, (Float) value);
                break;
            case "Long":
                editor.putLong(key, (Long) value);
                break;
        }
        // 异步提交
        editor.apply();
    }

    /**
     * 获取数据
     * @param fileName 文件名
     * @param key key值
     * @param defValue 默认值
     * @return 对应数据
     */
    public Object get(String fileName, String key, Object defValue){
        // 获取类型
        String type = defValue.getClass().getSimpleName();
        // 实例化Sp
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        switch (type){
            case "Integer":
                return sp.getInt(key, (Integer) defValue);
            case "String":
                return sp.getString(key, (String) defValue);
            case "Boolean":
                return sp.getBoolean(key, (Boolean) defValue);
            case "Float":
                return sp.getFloat(key, (Float) defValue);
            case "Long":
                return sp.getLong(key, (Long) defValue);
        }
        return null;
    }

    /**
     * 清空所有数据
     * @param fileName 要清空数据的文件名
     */
    public void clear(String fileName){
        // 实例化Sp
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.apply();
    }
}
